package com.sf.framework.servlet;


import com.sf.framework.annotaction.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *  调度器
 */
public class SFDispatchServletBak extends HttpServlet {

    private Properties properties = new Properties();

    private List<String> classNameList = new ArrayList<>();

    private Map<String,Object> ioc = new HashMap<String,Object>();

    //保存所有的Url和方法的映射关系
    private List<Handler> handlerMapping = new ArrayList<Handler>();

    @Override
    public void init(ServletConfig config) throws ServletException {
        //1.加载 配置文件
        doLoadConfig(config);
        //2.扫描包
        doScannerPackage(properties.getProperty("scanner.package"));
        //3.注入容器
        doInstance();
//        //4.依赖注入
        doAutowired();
//        //5.初始化handlerMapping
        initHandlerMapping();
        System.out.println("SFFramework init success!");
    }

    /**
     *  DI 注入
     */
    private void doAutowired() {
        if(ioc.isEmpty()) return;
        for (Map.Entry entry:ioc.entrySet()) {
            //获取 当前 对象的 所有属性
            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();
            for (Field field : declaredFields){
                if(!field.isAnnotationPresent(SFAutowrite.class)) continue;
                SFAutowrite annotation = field.getAnnotation(SFAutowrite.class);
                //自定义
                String beanName = annotation.value().trim();
                if("".equals(beanName)){
                    //根据 class 类型获取
                    beanName = field.getType().getName();
                }
                //设置私有属性的访问权限
                field.setAccessible(true);
                try {
                    field.set(entry.getValue(),ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    continue;
                }
            }
        }
    }

    private void initHandlerMapping() {
        if(ioc.isEmpty()){ return; }

        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();
            if(!clazz.isAnnotationPresent(SFController.class)){ continue; }

            String url = "";
            //获取Controller的url配置
            if(clazz.isAnnotationPresent(SFRequestMapping.class)){
                SFRequestMapping requestMapping = clazz.getAnnotation(SFRequestMapping.class);
                url = requestMapping.value();
            }

            //获取Method的url配置
            Method[] methods = clazz.getMethods();
            for (Method method : methods) {

                //没有加RequestMapping注解的直接忽略
                if(!method.isAnnotationPresent(SFRequestMapping.class)){ continue; }

                //映射URL
                SFRequestMapping requestMapping = method.getAnnotation(SFRequestMapping.class);
                String regex = ("/" + url + requestMapping.value()).replaceAll("/+", "/");
                Pattern pattern = Pattern.compile(regex);
                handlerMapping.add(new Handler(pattern,entry.getValue(),method));
                System.out.println("mapping " + regex + "," + method);
            }
        }
    }

    private void doInstance() {
        if(classNameList!=null && classNameList.size()>0){
            classNameList.forEach(className->{
                try {
                    Class<?> aClass = Class.forName(className);
                    if(aClass.isAnnotationPresent(SFController.class)){
                        Object object = aClass.newInstance();
                        String beanName = lowerFirstCase(aClass.getSimpleName());
                        ioc.put(beanName,object);
                    }else if(aClass.isAnnotationPresent(SFService.class)){
                        SFService annotation = aClass.getDeclaredAnnotation(SFService.class);
                        //1.自定义
                        String beanName = annotation.value();
                        if("".equals(beanName.trim())){
                            // 2.首字母大写
                            beanName = lowerFirstCase(aClass.getSimpleName());
                        }
                        Object object = aClass.newInstance();
                        ioc.put(beanName,object);


                        //3.按类型
                        Class<?>[] interfaces = aClass.getInterfaces();
                        for (Class classs:interfaces) {
                            if(ioc.containsKey(classs.getName())) throw new Exception("this".concat(classs.getName()).concat("is exists!"));
                            ioc.put(classs.getName(),object);
                        }
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }

    /**
     *  char 即 ascii 码
     *  小写 + 32 就会变成大写
     * @param simpleName
     * @return
     */
    private String lowerFirstCase(String simpleName) {
        char[] chars = simpleName.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

    private void doScannerPackage(String scannerPackage) {
        // 包名 转换成 文件层级  所以需要把 . 替换成为 /
        URL resources = this.getClass().getClassLoader().getResource("/"+scannerPackage.replaceAll("\\.","/"));
        File file = new File(resources.getFile());
        //循环获取 目录中 的class 文件名
        handlerClassName(file,scannerPackage);
    }

    private void handlerClassName(File file,String scannerPackage) {
        if(file.isDirectory()){
            //目录
            File[] files = file.listFiles();
            for (File f : files){
                if(f.isDirectory()){
                    //此处 f.getName() 获得 文件名 TestController.class
                    handlerClassName(f,scannerPackage+"."+f.getName());
                }else{
                    //加入 全限定包名
                    classNameList.add(scannerPackage+"."+f.getName().replaceAll(".class",""));
                }
            }
        }else{
            //文件
            if(file.getName().endsWith(".class"))classNameList.add(scannerPackage+"."+file.getName().replaceAll(".class",""));
        }
    }

    private void doLoadConfig(ServletConfig config) {
        String fileName = config.getInitParameter("contextConfigLocation");
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(fileName);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            System.out.println("配置文件加载失败！");
            e.printStackTrace();
        }finally {
            try {
                if(resourceAsStream != null){
                    resourceAsStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //派遣
        try {
            doDispatch(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void doDispatch(HttpServletRequest req,HttpServletResponse resp) throws Exception {
        try{
            Handler handler = getHandler(req);

            if(handler == null){
                //如果没有匹配上，返回404错误
                resp.getWriter().write("404 Not Found");
                return;
            }


            //获取方法的参数列表
            Class<?> [] paramTypes = handler.method.getParameterTypes();

            //保存所有需要自动赋值的参数值
            Object [] paramValues = new Object[paramTypes.length];


            Map<String,String[]> params = req.getParameterMap();
            for (Map.Entry<String, String[]> param : params.entrySet()) {
                String value = Arrays.toString(param.getValue()).replaceAll("\\[|\\]", "").replaceAll(",\\s", ",");

                //如果找到匹配的对象，则开始填充参数值
                if(!handler.paramIndexMapping.containsKey(param.getKey())){continue;}
                int index = handler.paramIndexMapping.get(param.getKey());
                paramValues[index] = convert(paramTypes[index],value);
            }


            //设置方法中的request和response对象
            int reqIndex = handler.paramIndexMapping.get(HttpServletRequest.class.getName());
            paramValues[reqIndex] = req;
            int respIndex = handler.paramIndexMapping.get(HttpServletResponse.class.getName());
            paramValues[respIndex] = resp;

            handler.method.invoke(handler.controller, paramValues);

        }catch(Exception e){
            throw e;
        }
    }

    private Handler getHandler(HttpServletRequest req) throws Exception{
        if(handlerMapping.isEmpty()){ return null; }

        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = url.replace(contextPath, "").replaceAll("/+", "/");

        for (Handler handler : handlerMapping) {
            try{
                Matcher matcher = handler.pattern.matcher(url);
                //如果没有匹配上继续下一个匹配
                if(!matcher.matches()){ continue; }

                return handler;
            }catch(Exception e){
                throw e;
            }
        }
        return null;
    }

    //url传过来的参数都是String类型的，HTTP是基于字符串协议
    //只需要把String转换为任意类型就好
    private Object convert(Class<?> type,String value){
        if(Integer.class == type){
            return Integer.valueOf(value);
        }
        //如果还有double或者其他类型，继续加if
        //这时候，我们应该想到策略模式了
        //在这里暂时不实现，希望小伙伴自己来实现
        return value;
    }



    /**
     * Handler记录Controller中的RequestMapping和Method的对应关系
     * @author Tom
     * 内部类
     */
    private class Handler{

        protected Object controller;	//保存方法对应的实例
        protected Method method;		//保存映射的方法
        protected Pattern pattern;
        protected Map<String,Integer> paramIndexMapping;	//参数顺序

        /**
         * 构造一个Handler基本的参数
         * @param controller
         * @param method
         */
        protected Handler(Pattern pattern,Object controller,Method method){
            this.controller = controller;
            this.method = method;
            this.pattern = pattern;

            paramIndexMapping = new HashMap<String,Integer>();
            putParamIndexMapping(method);
        }

        private void putParamIndexMapping(Method method){

            //提取方法中加了注解的参数
            Annotation[] [] pa = method.getParameterAnnotations();
            for (int i = 0; i < pa.length ; i ++) {
                for(Annotation a : pa[i]){
                    if(a instanceof SFRequestParam){
                        String paramName = ((SFRequestParam) a).value();
                        if(!"".equals(paramName.trim())){
                            paramIndexMapping.put(paramName, i);
                        }
                    }
                }
            }

            //提取方法中的request和response参数
            Class<?> [] paramsTypes = method.getParameterTypes();
            for (int i = 0; i < paramsTypes.length ; i ++) {
                Class<?> type = paramsTypes[i];
                if(type == HttpServletRequest.class ||
                        type == HttpServletResponse.class){
                    paramIndexMapping.put(type.getName(),i);
                }
            }
        }
    }
}
